package com.rmy.queue.api.utils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.security.cert.X509Certificate;
import java.util.HashMap;

public class WebUtils {

    public static String httpRequest(String token, String sendUrl, String sendType, String postData) {
        java.net.URL url = null;
        HttpURLConnection httpurlconnection = null;
        //logger.info("HTTPRequest(请求连接是："+sendUrl+",请求参数是："+postData+")");
        try {

            url = new java.net.URL(sendUrl);
            httpurlconnection = (HttpURLConnection) url.openConnection();
            boolean useHttps = sendUrl.startsWith("https");
            if (useHttps) {
              HttpsURLConnection https = (HttpsURLConnection) httpurlconnection;
              trustAllHosts(https);
              https.setHostnameVerifier(DO_NOT_VERIFY);
            }
            httpurlconnection.setRequestMethod(sendType);
            if (!"".equals(token) && token != null) {
                httpurlconnection.setRequestProperty("Authorization", "Bearer "+token);
            }
            httpurlconnection.setRequestProperty("Content-Type", "application/json");
            httpurlconnection.setDoInput(true);
            httpurlconnection.setDoOutput(true);

            // 设置http请求超时时间30000毫秒（30秒）
            httpurlconnection.setConnectTimeout(30000);
            httpurlconnection.setReadTimeout(30000);
            httpurlconnection.setUseCaches(true);

            if (sendType.equalsIgnoreCase("POST")) {
                httpurlconnection.getOutputStream().write(postData.getBytes("UTF-8"));
                httpurlconnection.getOutputStream().flush();
                httpurlconnection.getOutputStream().close();
            }

            int code = httpurlconnection.getResponseCode();
            if (code == 200) {
                //得到输入流
                java.io.InputStream is = httpurlconnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String strRead = null;
                StringBuffer sbf = new StringBuffer();
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                }
                reader.close();
                String rev = sbf.toString();
                is.close();
                System.out.println("\nAPI返回的结果：\n" + rev);
                return rev;
            } else {
                // http 请求返回非 200状态时处理
                return httpurlconnection.getResponseMessage();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
        }
        return null;
    }

    /**
       * 信任所有
       * @param connection
       * @return
       */
      private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
        SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
        try {
          SSLContext sc = SSLContext.getInstance("TLS");
          sc.init(null, trustAllCerts, new java.security.SecureRandom());
          SSLSocketFactory newFactory = sc.getSocketFactory();
          connection.setSSLSocketFactory(newFactory);
        } catch (Exception e) {
          e.printStackTrace();
        }
        return oldFactory;
      }

        /**
          * 覆盖java默认的证书验证
          */
      private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
             public X509Certificate[] getAcceptedIssuers() {
                 return new X509Certificate[]{};
             }

             public void checkClientTrusted(X509Certificate[] chain, String authType) {
             }

             public void checkServerTrusted(X509Certificate[] chain, String authType) {
             }
         }};

      /**
       * 设置不验证主机
       */
      private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
          return true;
        }
      };

	public static void main(String[] args) {
		String host = "http://cdetail.market.alicloudapi.com";
		String path = "/lianzhuo/cdetails";
		String method = "GET";
		String appcode = "51024d75d89a4454a01df40534c89f6c";
		java.util.Map<String, String> headers = new HashMap<String, String>();
		//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE " + appcode);
		java.util.Map<String, String> querys = new HashMap<String, String>();
		querys.put("keyword", "浙江青亭信息科技有限公司");

		WebUtils.httpRequest("",
			"https://loan.shyrcb.com/wx/creditmarket/creditmarket/callNumber/onlineCallSave",
			"POST", "{\"callDate\":\"6954ff85a5dbd095d8171ab6feb2c8761323c131564ba76ec0cfa7b0f542cc633e568268aaf4e92b9bbfee4e199d18c6b42332c9423913ee07ceecc6db63a45f99f6e4dd4680230b355d631688b82f0f951365c29e94487452e26fd1dcede6179b604b7e2efb1e9ce59b95ea18ce68d14a5513576c15a8c4b7e7c495244e764842dc2c99d27cf3ca3aca6bcc4cd2edef45ae470de29ea642d4689cea88e0290f6e498d4d865f284584ac96d1825fd5fb890e907571a0431b23f45b3fdca7ff745722f48fe1ad787f4853a51f5f9c22837b7b6927748596277bc8696d2bac989408985d944542717d90c59e295abb43c9b0bc0454e76f3d082cb595855a0badaf\"}");

		try {

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
